<template>
	<view style="height: 100%;">
		<view class="page__content">

			<view class="page__content__main">
				<view class="ble__card">
					<view class="ble__card__top">
						<text>已配对设备</text>
					</view>

					<view class="ble__card__content">
						<template v-if="isLinkDevice.length">

							<u-cell v-for="item in isLinkDevice" :key="item.deviceId">
								<template #title>
									<view class="x-f">
										<view style="color: #333;margin-left: 10px;">
											<text>{{item.aliasName || item.name}}</text>
										</view>
									</view>
								</template>

								<template #label>
									<text v-if="item.connected"
										style="margin-left: 10px;color: #05bc4f;font-size: 12px;">已连接</text>
									<text v-else style="margin-left: 10px;color: #999;font-size: 12px;">未连接</text>
								</template>

								<template #value>
									<view @click="handlerClickToLink(item)">
										<u-icon name="setting-fill" color="#333" size="24"></u-icon>
									</view>
								</template>
							</u-cell>
						</template>

						<template v-else>
							<view class="x-c" style="height: 80px;font-size: 12px;color: #999;">
								<text>暂无已配对设备！</text>
							</view>
						</template>

					</view>
				</view>

				<view class="ble__card">
					<view class="ble__card__top">
						<text>可用设备</text>
					</view>

					<view class="ble__card__content">
						<u-cell v-for="item in deviceList" :key="item.deviceId">
							<template #title>
								<view class="x-f">
									<volume :num="item.RSSI"></volume>

									<view style="color: #333;margin-left: 10px;">
										<text>{{item.aliasName || item.name}}</text>
									</view>
								</view>
							</template>
							<template #value>
								<button type="primary" size="mini" @click="connectDevice(item)">
									<text style="font-size: 12px;">连接</text>
								</button>
							</template>
						</u-cell>
					</view>
				</view>

			</view>


			<view class="page__content__bottom x-ec">



				<button v-if="!$bluetooth.isDiscovering" class="btn CommonBtnSize" type="primary"
					@click="startScan">开始扫描</button>

				<template v-else>

					<button class="btn CommonBtnSize" type="primary" @click="refreshScan">刷新列表</button>

					<button class="btn CommonBtnSize" type="warn" @click="stopScan">停止扫描</button>
				</template>
			</view>
		</view>


	</view>
</template>

<script>
	import volume from "@/st_qms/control/Device/signal.vue";
	export default {
		components: {
			volume
		},
		props: {
			choiceDeviceInfo: {
				type: Object,
				default: {}
			}
		},
		data() {
			return {
				pageConfig: {},
				// 检索到的设备数据
				deviceList: [],
				deviceMap: {},
				currentDevice: null, // 当前连接的设备
				isConnected: false, // 连接状态

				isLinkDevice: [],

				deviceConfig: {
					showPopup: false,
					formMenus: [{
						name: '取消配对',
						value: '',
						icon: 'reload',
						show: true,
					}, {
						name: '设置别名',
						value: '',
						icon: 'reload',
						show: true,
					}, ],
					setName: false,
					changeName: "",
					tempDeviceInfo: {},
					bluetoothType: false, // 蓝牙适配器是否开启
					RSSI: 0,


					findDevice: false, // 是否查询到设备
					showLoading: false,
					scanTimer: null
				}
			}
		},
		created() {
			let that = this;

			this.$bluetooth.openBluetooth();

			console.log(this.choiceDeviceInfo.BluetoothProtocol);
			this.filterByBluetoothProtocol();

			this.startScan();

		},
		beforeDestroy() {
			this.$bluetooth.stopDiscovery();
		},
		methods: {
			filterByBluetoothProtocol() {
				console.log(this.$store.state.bluetooth.connectedDevices);



				// 将对象的值转为数组，再筛选出BluetoothProtocol匹配的项
				let result = Object.values(this.$store.state.bluetooth.connectedDevices).filter(device => {
					// 确保设备有config且包含BluetoothProtocol字段，避免报错
					return device.config?.BluetoothProtocol === this.choiceDeviceInfo.BluetoothProtocol;
				});
				console.log(result);
				this.isLinkDevice = result;
			},
			// 开始扫描
			startScan() {
				let that = this;

				// 清除可能存在的旧计时器，避免重复计时
				if (this.deviceConfig.scanTimer) {
					clearInterval(this.deviceConfig.scanTimer);
					this.deviceConfig.scanTimer = null;
				}

				// 重置扫描状态
				this.deviceConfig.showLoading = true; // 显示加载中
				this.deviceConfig.findDevice = false; // 标记是否在本轮5秒内找到设备
				let currentSecond = 0; // 当前计时秒数


				this.$bluetooth.startDiscovery(devices => {
					console.log('原始扫描设备列表:', devices);

					// 处理弹层开启时的设备过滤逻辑（保持不变）
					if (that.deviceConfig.showPopup) {
						const currentDeviceId = that.deviceConfig.tempDeviceInfo?.deviceId;
						if (devices.length) {
							const targetDevice = devices.find(item => item.deviceId === currentDeviceId);
							if (targetDevice) {
								that.$set(that.deviceConfig, "RSSI", targetDevice.RSSI);
								that.deviceConfig.findDevice = true;
								that.deviceConfig.showLoading = false;
							}
						}
					}

					// 关键：批量处理设备别名并去重
					let list = [...that.deviceList];
					// 从蓝牙管理器获取内存中的别名映射表（一次获取，批量使用）
					const aliasMap = this.$bluetooth.aliasMap;

					for (let i = 0; i < devices.length; i++) {
						let dev = devices[i];
						// 1. 绑定别名（从内存映射表直接获取，O(1)复杂度）
						const alias = aliasMap[dev.deviceId];
						if (alias) {
							// 用$set保证响应式（如果需要在视图中实时更新）
							that.$set(dev, 'aliasName', alias);
						} else {
							// 无别名时用原始名称（避免undefined）
							that.$set(dev, 'aliasName', dev.name || dev.localName || '未知设备');
						}

						// 2. 原有去重逻辑（保持不变，但基于处理后的dev）
						if (that.deviceMap[dev.deviceId] !== undefined) {
							let index = that.deviceMap[dev.deviceId];
							list.splice(index, 1, dev);
						} else {
							list.push(dev);
							that.deviceMap[dev.deviceId] = list.length - 1;
						}
					}

					that.deviceList = list;
				});

				// 启动5秒计时器（每秒检查一次）
				this.deviceConfig.scanTimer = setInterval(() => {
					currentSecond++; // 每秒累加

					// 当计时达到5秒时
					if (currentSecond >= 5) {
						if (that.deviceConfig.findDevice) {
							// 情况1：本轮5秒内找到设备 → 重置计时，进入下一轮5秒
							currentSecond = 0; // 重置秒数
							that.deviceConfig.findDevice = false; // 重置标记（等待下一轮判断）
							console.log("找到设备，进入下一轮5秒扫描");
						} else {
							// 情况2：本轮5秒内未找到设备 
							that.deviceConfig.scanTimer = null;
							that.deviceConfig.showLoading = false; // 隐藏加载中
							that.deviceConfig.findDevice = false; // 标记未找到
							currentSecond = 0;
						}
					}
				}, 1000); // 每秒执行一次检查
			},

			// 停止扫描
			stopScan() {

				// 情况2：本轮5秒内未找到设备 → 停止扫描
				clearInterval(this.deviceConfig.scanTimer); // 清除计时器
				this.$bluetooth.stopDiscovery();
			},
			refreshScan() { // 刷新扫描列表
				this.deviceMap = {};
				this.deviceList = [];

			},

			getLinkDev() {
				console.log(this.$store.state.bluetooth.connectedDevices);
			},

			// 断开当前设备
			disconnectCurrent(deviceObj) {
				this.$bluetooth.disconnectDevice(deviceObj.deviceId);
			},

			// 连接设备
			async connectDevice(deviceObj) {
				let that = this;

				this.$bluetooth.connectDevice(deviceObj, this.choiceDeviceInfo, () => {
					console.log(1111);
					// 删除查询列表中已连接的蓝牙信息
					that.deviceList = that.deviceList.filter(item => {
						return deviceObj.deviceId != item.deviceId;
					})

					that.filterByBluetoothProtocol();
				});
			},


			// 对已配对的数据进行操作
			connectDeviceByReady(deviceObj) {

				switch (deviceObj.connected) {
					case true: // 已连接--去断开
						this.disconnectCurrent(deviceObj);


						break;
					case false: // 已断开--去连接
						this.connectDevice(deviceObj);

						break;
					default:
						break;
				}

			},

			async handlerClickToLink(data) { // 点击已配对设备，打开弹层
				let that = this;
				// this.$set(this.deviceConfig, 'tempDeviceInfo', data);
				// this.deviceConfig.tempDeviceInfo = data;
				// this.deviceConfig.showPopup = true;

				// this.deviceConfig.bluetoothType = true;
				// const linkType = await this.$bluetooth.isConnected(this.deviceConfig.tempDeviceInfo.deviceId);

				// // 判断当前设备是否连接
				// if (!linkType) { // 未连接
				// 	// 开启扫描
				// 	this.deviceConfig.findDevice = true;
				// 	this.deviceConfig.showLoading = true;
				// 	this.startScan();
				// };
				uni.navigateTo({
					url: "/st_qms/Bluetooth/device_link" + "?deviceId=" + data.deviceId,
					events: {
						cancel: function(data) {
							console.log(data);

							// 停止搜索再开启

							that.stopScan();
							that.startScan();
						},
						setName: function() { // 确认设置别名
							// 刷新一下
							console.log("已设置别名");
						}
					}
				})

			},
			close_device_popup() { // 关闭设备连接弹层
				if (this.deviceConfig.setName) {
					this.deviceConfig.setName = false;
					this.deviceConfig.changeName = "";
					return;
				}

				this.deviceConfig.showPopup = false;
				// 停止扫描和计时器
				if (this.deviceConfig.scanTimer) {
					clearInterval(this.deviceConfig.scanTimer);
					this.deviceConfig.scanTimer = null;
				}
			},
			deviceConfig_popup_menu(data) { // 点击弹层气泡
				switch (data.name) {
					case "取消配对":
						// 1、断开连接
						this.$bluetooth.disconnectDevice(this.deviceConfig.tempDeviceInfo.deviceId);

						const deviceInfo = this.$utils.deepClone(this.$store.state.bluetooth.connectedDevices);
						// 2、删除设备信息
						Object.keys(deviceInfo).forEach(item => {
							delete deviceInfo[this.deviceConfig.tempDeviceInfo.deviceId]
						});


						this.$store.commit("bluetooth/ChangeAndSetStateData", {
							Name1: 'connectedDevices',
							data: deviceInfo,
							StorageName: "connectedDevices",
							StorageData: JSON.stringify(deviceInfo)
						});
						this.filterByBluetoothProtocol();

						// 关闭弹层
						this.close_device_popup();

						break;
					case "设置别名":

						this.deviceConfig.setName = true;
						this.deviceConfig.changeName = this.deviceConfig.tempDeviceInfo.aliasName ? this.deviceConfig
							.tempDeviceInfo.aliasName : this.deviceConfig.tempDeviceInfo.name;


						break;
					default:
						break;
				}
			},
			async handlerClickByLink() {
				let that = this;
				const deviceType = this.deviceConfig.tempDeviceInfo.connected;
				switch (deviceType) {
					case true:
						uni.showLoading({
							title: "正在断开"
						})
						// 断开设备
						this.$bluetooth.disconnectDevice(this.deviceConfig.tempDeviceInfo.deviceId, () => {
							uni.hideLoading();
							// 重新设置蓝牙状态
							this.deviceConfig.tempDeviceInfo.connected = false;
							// 开启扫描
							this.startScan();
						});

						break;
					case false:
						// 判断是否查询到设备
						if (this.deviceConfig.findDevice) {
							// 连接设备
							uni.showLoading({
								title: "正在连接"
							})
							console.log(this.deviceConfig.tempDeviceInfo);
							this.$bluetooth.connectDevice(this.deviceConfig.tempDeviceInfo, this.deviceConfig
								.tempDeviceInfo.config, () => {
									uni.hideLoading();

									that.deviceConfig.showLoading = false;
									that.deviceConfig.tempDeviceInfo.connected = true;


									if (that.deviceConfig.scanTimer) {
										clearInterval(that.deviceConfig.scanTimer);
									}
									that.stopScan();

								});

						} else {
							// 连接设备
							uni.showLoading({
								title: "正在扫描"
							})
							// 未查询到，刷新重试
							this.startScan();

						}

						break;
					default:
						break;
				}

			},

			// 检查是否是当前设备
			isCurrentDevice(device) {
				return this.currentDevice && this.currentDevice.deviceId === device.deviceId;
			}
		}
	}
</script>

<style lang="scss">
	.page__content {
		height: 100%;
		background-color: #f9f9f9;

		&__main {
			padding: 15px;

			.ble__card {
				padding: 15px;
				border-radius: 15px;

				&__top {
					padding: 8px 0;
					font-size: 14px;
					color: #999;
				}

				&__content {
					background-color: #fff;
					color: #333;
					// min-height: 100px;
					border-radius: 15px;
					overflow: hidden;
				}
			}


		}

		&__bottom {
			padding: 15px;

			.btn {
				margin-left: 10px;
			}
		}
	}

	.connection-status {
		padding: 20rpx;
		background-color: #f5f5f5;
		border-radius: 8rpx;
		margin: 20rpx;
	}

	.status-text {
		display: block;
		font-size: 28rpx;
		color: #333;
		margin-bottom: 10rpx;
	}
</style>